package com.hsogoo.study.spring.beanfactorypostprocessor;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

/**
 * Created by za-huangsaigang on 2018/9/17.
 */
public class PropertySourcesPlaceholderConfigurerTest {

    @Test
    public void testPropertySourcesPlaceholderConfigurer(){
        //创建一个BeanFactory，并注册一个bean，bean的类名用占位符表示
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        RootBeanDefinition beanDefinition = new RootBeanDefinition("${beanName}");
        beanDefinition.setScope("${scope}");
        factory.registerBeanDefinition("myBean", beanDefinition);
        //创建一个PropertySourcesPlaceholderConfigurer，
        //并加入含有占位符字符串对应的 MutablePropertySources
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        Map<String, Object> map = new HashMap<>();
        map.put("beanName", "com.hsogoo.study.spring.resource.ResourceLoaderBean");//占位符对应
        map.put("scope", RootBeanDefinition.SCOPE_PROTOTYPE);//占位符对应“prototype”

        MutablePropertySources sources = new MutablePropertySources();
        sources.addLast(new MapPropertySource("mapSource", map));

        configurer.setPropertySources(sources);

        //对 BeanFactory增强，会替换掉占位符
        configurer.postProcessBeanFactory(factory);

        System.out.println(factory.getBeanDefinition("myBean"));
        System.out.println(factory.getBean("myBean"));
    }
}
